/*
 * Copyright (C) 2013 Leszek Mzyk
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.adeaz.sdk.demo.wow;

import android.content.Context;
import android.os.Handler;
import android.os.Message;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.util.AttributeSet;
import android.view.MotionEvent;

import java.util.Timer;
import java.util.TimerTask;

/**
 * A ViewPager subclass enabling infinte scrolling of the viewPager elements
 * <p>
 * When used for paginating views (in opposite to fragments), no code changes
 * should be needed only change xml's from <android.support.v4.view.ViewPager>
 * to <com.imbryk.viewPager.LoopViewPager>
 * <p>
 * If "blinking" can be seen when paginating to first or last view, simply call
 * seBoundaryCaching( true ), or change DEFAULT_BOUNDARY_CASHING to true
 * <p>
 * When using a FragmentPagerAdapter or FragmentStatePagerAdapter, additional
 * changes in the adapter must be done. The adapter must be prepared to create 2
 * extra items e.g.:
 * <p>
 * The original adapter creates 4 items: [0,1,2,3] The modified adapter will
 * have to create 6 items [0,1,2,3,4,5] with mapping
 * realPosition=(position-1)%count [0->3, 1->0, 2->1, 3->2, 4->3, 5->0]
 */
public class LoopPager extends ViewPager {


    OnPageChangeListener mOuterPageChangeListener;

    /**
     * A timer and a TimerTask using to cycle
     */
    private Timer mCycleTimer;
    private TimerTask mCycleTask;

    /**
     * For resuming the cycle, after user touch or click
     */
    private Timer mResumingTimer;
    private TimerTask mResumingTask;

    /**
     * the duration between animation.
     */
    private int mDuration = 4000;

    /**
     * Cycling
     */
    private boolean mCycling;

    /**
     * Determine if auto recover after user touch
     */
    private boolean mAutoRecover = true;

    /**
     * auto cycle
     */
    private boolean mAutoCycle = true;

    /**
     * Ban sliding
     */
    private boolean mNoScroll = false;


    /**
     * If set to true, the boundary views (i.e. first and last) will never be
     * destroyed This may help to prevent "blinking" of some views
     *
     * @param
     */

    @Override
    public void setAdapter(PagerAdapter adapter) {
        super.setAdapter(adapter);
        //设置缓存的页面数量
//        setOffscreenPageLimit(adapter.getCount());
        setCurrentItem(0, false);
    }

    @Override
    public void setCurrentItem(int item) {
        if (getCurrentItem() != item) {
            setCurrentItem(item, true);
        }
    }

    @Override
    public void setOnPageChangeListener(OnPageChangeListener listener) {
        mOuterPageChangeListener = listener;
    }


    public LoopPager(Context context) {
        super(context);
        init();
    }

    public LoopPager(Context context, AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    private void init() {
        super.setOnPageChangeListener(onPageChangeListener);
    }

    private OnPageChangeListener onPageChangeListener = new OnPageChangeListener() {
        private float mPreviousOffset = -1;
        private float mPreviousPosition = -1;

        @Override
        public void onPageSelected(int position) {
            int realPosition = position;
            if (mPreviousPosition != realPosition) {
                mPreviousPosition = realPosition;
                if (mOuterPageChangeListener != null) {
                    mOuterPageChangeListener.onPageSelected(realPosition);
                }
            }
        }

        @Override
        public void onPageScrolled(int position, float positionOffset,
                                   int positionOffsetPixels) {
            int realPosition = position;
            if (getAdapter() != null) {
                realPosition = position;
                if (positionOffset == 0
                        && mPreviousOffset == 0
                        && (position == 0 || position == getAdapter().getCount() - 1)) {
                    setCurrentItem(realPosition, false);
                }
            }

            mPreviousOffset = positionOffset;
            if (mOuterPageChangeListener != null) {
                if (realPosition != getAdapter().getCount() - 1) {
                    mOuterPageChangeListener.onPageScrolled(realPosition,
                            positionOffset, positionOffsetPixels);
                } else {
                    if (positionOffset > .5) {
                        mOuterPageChangeListener.onPageScrolled(0, 0, 0);
                    } else {
                        mOuterPageChangeListener.onPageScrolled(realPosition,
                                0, 0);
                    }
                }
            }
        }

        @Override
        public void onPageScrollStateChanged(int state) {
            if (getAdapter() != null) {
                int position = LoopPager.super.getCurrentItem();
                int realPosition = position;
                if (state == ViewPager.SCROLL_STATE_IDLE
                        && (position == 0 || position == getAdapter().getCount() - 1)) {
                    setCurrentItem(realPosition, false);
                }
            }
            if (mOuterPageChangeListener != null) {
                mOuterPageChangeListener.onPageScrollStateChanged(state);
            }
        }
    };

    /**
     * when paused cycle, this method can weak it up.
     */
    private void recoverCycle() {
        if (!mAutoRecover || !mAutoCycle) {
            return;
        }

        if (!mCycling) {
            if (mResumingTask != null && mResumingTimer != null) {
                mResumingTimer.cancel();
                mResumingTask.cancel();
            }
            mResumingTimer = new Timer();
            mResumingTask = new TimerTask() {
                @Override
                public void run() {
                    startAutoCycle();
                }
            };
            mResumingTimer.schedule(mResumingTask, 6000);
        }
    }

    /**
     * set the duration between two slider changes. the duration value must >=
     * 500
     *
     * @param duration
     */
    public void setDuration(int duration) {
        if (duration >= 500) {
            mDuration = duration;
        }
    }

    /**
     * stop the auto circle
     */
    public void stopAutoCycle() {
        if (mCycleTask != null) {
            mCycleTask.cancel();
        }
        if (mCycleTimer != null) {
            mCycleTimer.cancel();
        }
        if (mResumingTimer != null) {
            mResumingTimer.cancel();
        }
        if (mResumingTask != null) {
            mResumingTask.cancel();
        }

        mAutoCycle = false;
        mCycling = false;
    }

    /**
     * pause auto cycle.
     */
    public void pauseAutoCycle() {
        if (mCycling) {
            mCycleTimer.cancel();
            mCycleTask.cancel();
            mCycling = false;
        } else {
            if (mResumingTimer != null && mResumingTask != null) {
                recoverCycle();
            }
        }
    }

    /**
     * start the auto circle
     */
    public void startAutoCycle() {
        startAutoCycle(mDuration);
    }

    /**
     * Ban sliding
     *
     * @param noScroll
     */
    public void setNoTouchScroll(boolean noScroll) {
        this.mNoScroll = noScroll;
    }

    /**
     * start the auto circle
     *
     * @param duration
     */
    public void startAutoCycle(int duration) {
        if (mCycleTimer != null)
            mCycleTimer.cancel();
        if (mCycleTask != null)
            mCycleTask.cancel();
        if (mResumingTask != null)
            mResumingTask.cancel();
        if (mResumingTimer != null)
            mResumingTimer.cancel();
        mDuration = duration;
        mCycleTimer = new Timer();
        mCycleTask = new TimerTask() {
            @Override
            public void run() {
                mh.sendEmptyMessage(0);
            }
        };
        mCycleTimer.schedule(mCycleTask, duration, duration);

        mCycling = true;
        mAutoCycle = true;
    }

    private Handler mh = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            if (getAdapter() != null && getAdapter().getCount() > 1) {
                //当到达最后一个的时候回到第一个，去除滑动
                if (getCurrentItem() == getAdapter().getCount() - 1)
                    setCurrentItem(0, false);
                else
                    setCurrentItem(getCurrentItem() + 1, true);
            }
        }
    };

    @Override
    public boolean onTouchEvent(MotionEvent event) {

        int action = event.getAction();
        switch (action) {
            case MotionEvent.ACTION_DOWN:
                pauseAutoCycle();
                break;
            case MotionEvent.ACTION_UP:
                if (mAutoCycle) {
                    startAutoCycle();
                }
                break;
        }
        if (mNoScroll)
            return false;
        return super.onTouchEvent(event);
    }

    @Override
    public boolean onInterceptTouchEvent(MotionEvent arg0) {
        if (mNoScroll)
            return false;
        else
            return super.onInterceptTouchEvent(arg0);
    }

}
